package assignment.day3;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

@WebServlet(description = "day3 assignment 3  login control servlet", urlPatterns = { "/D3A3WelcomeServlet" })
public class D3A3WelcomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/*
	 * ServletConfig config; ServletContext context;
	 * 
	 * @Override public void init(ServletConfig config) throws ServletException
	 * { this.config = config; context = config.getServletContext(); }
	 */

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.getWriter()
				.write("Get method is not defined. use Post method");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			/*
			 * Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con
			 * = DriverManager.getConnection(
			 * "jdbc:oracle:thin:@10.23.0.100:1521:esgdb10", "scott", "tiger");
			 */
			/*
			 * Class.forName("org.postgresql.Driver"); Connection con =
			 * DriverManager.getConnection(
			 * "jdbc:postgresql://localhost:5432/jee", "karthik", "tiger");
			 */
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("jdbc/mydata");
			Connection con = ds.getConnection();

			// int count = Integer.parseInt((String)
			// request.getAttribute("attempts"));

			String username = request.getParameter("username");
			String password = request.getParameter("password");

			HttpSession session = request.getSession(true);

			PreparedStatement s = con
					.prepareStatement("select * from mywebusers where username=?");
			s.setString(1, username);
			ResultSet rs = s.executeQuery();// +
											// username);
			rs.next();
			System.out.println("run");
			if (rs.getString(2).equals(password)) {
				session.setAttribute("username", username);
				RequestDispatcher rd = getServletConfig().getServletContext()
						.getRequestDispatcher("/D3A3ProductServlet");
				rd.forward(request, response);
			} else {
				session.invalidate();
				response.sendRedirect("./d3a3-login.jsp");
			}
			s.close();
			con.close();
		} catch (Exception e) {
			response.setContentType("text/html");
			response.getWriter().write(e.toString());
		}
	}
}
